<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH.'controllers/Base.php';

use \QCloud_WeApp_SDK\Auth\LoginService as LoginService;
use QCloud_WeApp_SDK\Constants as Constants;

class User extends Base {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
    }

    public function index() {
        $result = LoginService::check();

        if ($result['loginState'] === Constants::S_AUTH) {
            $this->json([
                'code' => 0,
                'data' => $result['userinfo']
            ]);
        } else {
            $this->json([
                'code' => -1,
                'data' => []
            ]);
        }
    }

    public function register()
    {
        $result = LoginService::check();
        if($result['loginState'] === Constants::E_AUTH){
            $this->error('微信未登录');
        }
        $userinfo = $result['userinfo'];
        $data['name'] = $this->input->post('name');
        $gender = $this->input->post('gender');
        $data['gender'] = $gender == 'male' ? 0 : 1;
        $data['telephone'] = $this->input->post('telephone');

        $user = $this->user_model->getWechatUser($userinfo['openId']);

        if($user){
            $this->user_model->updateUser($user['user_id'],$data);
        }else{
            $this->user_model->insertUser($userinfo,$data);
        }

        $this->success();

    }

    public function info()
    {
        $result = LoginService::check();
        if($result['loginState'] === Constants::E_AUTH){
            $this->error('微信未登录');
        }
        $userinfo = $result['userinfo'];

        $user = $this->user_model->getWechatUser($userinfo['openId']);

        if(empty($user)){
          $user = $this->user_model->insertUser($userinfo);
        }

        $this->success($user);
    }
}
